package com.cloudwave.trailends.action;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cloudwave.base.action.AppAction;
import com.cloudwave.base.entity.ResultEntity;
import com.cloudwave.fwcore.entity.Result;
import com.cloudwave.trailends.AppProerties;
import com.cloudwave.trailends.service.UserService;
import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.config.Config;
import com.qiniu.api.rs.PutPolicy;

/**
 * @description 处理文件上传请求
 * @author 龙雪
 * @email 3kqing@gmail.com
 * @date 2014-8-13 下午11:25:33
 * 
 */

@Controller
@RequestMapping("/api/upload")
public class UploadAction extends AppAction {
	private static Logger logger = LoggerFactory.getLogger(UploadAction.class);
	
	@Resource
	private UserService userService;
	
	@RequestMapping(value="/token")
	public @ResponseBody ResultEntity token(HttpServletRequest request) {
		Config.ACCESS_KEY = "ve3UUHI8LvEZYB5jG4w9TS3zuDCSkkq7zqt-KuqO";
        Config.SECRET_KEY = "a5WoF6wAEFa3AykKL3qxiW9rQpxfC2rqF-tQ2psJ";
        
        String action = request.getParameter("action");
        
        Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        // 请确保该bucket已经存在
        String bucketName = "onriding";
        PutPolicy putPolicy = new PutPolicy(bucketName);
        putPolicy.expires = 10800;  //失效时间为3个小时
        if ( StringUtils.isNotEmpty(action) ) {
        	putPolicy.saveKey = action+"_$(etag)";  //原本是想把上传的文件加上自己的前缀，然后文件名是唯一的，但目前这个参数不起作用
        } else {
        	putPolicy.saveKey = "$(etag)";  //原本是想把上传的文件加上自己的前缀，然后文件名是唯一的，但目前这个参数不起作用
        }
        
        putPolicy.callbackUrl= "http://api.onriding.cc/api/upload/qiniu/callback.html";
		//putPolicy.callbackUrl= "http://121.40.80.128:8182/qiniu/upload/callback.html";
        putPolicy.callbackBody = "bucket=${bucket}&key=$(key)&hash=$(etag)&width=$(imageInfo.width)&height=$(imageInfo.height)&size=${fsize}&mimeType=${mimeType}&userId="+super.userId;
//        putPolicy.callbackBody = "bucket=${bucket}&key=$(key)&hash=$(etag)&width=$(imageInfo.width)&height=$(imageInfo.height)&size=${fsize}&mimeType=${mimeType}&userId=1";
        
        String uptoken = "";
        
		try {
			uptoken = putPolicy.token(mac);
		} catch (AuthException e) {
			e.printStackTrace();
			return resultEntity.failure();
		} catch (JSONException e) {
			e.printStackTrace();
			return resultEntity.failure();
		}
		
		return resultEntity.success(uptoken);
	}
	
	@RequestMapping(value = "/qiniu/callback")
	private @ResponseBody Map<String, String> callback(@RequestParam("bucket") String bucket
			, @RequestParam("key") String key, @RequestParam("hash") String hash
			, @RequestParam("width") Integer width, @RequestParam("height") Integer height
			, @RequestParam("size") Integer size, @RequestParam("mimeType") String mimeType
			, @RequestParam("userId") Long userId) {
		
//		ImgResource resource = resourceService.findByHash(hash);
//		
//		if ( resource == null ) {
//			ImgResource newResource = new ImgResource();
//			newResource.setBucket(bucket);
//			newResource.setKey(key);
//			newResource.setHash(hash);
//			newResource.setWidth(width);
//			newResource.setHeight(height);
//			newResource.setSize(size);
//			newResource.setMimeType(mimeType);
//			newResource.setEditorId(editorId);
//			newResource.setUrl("http://7u2hs7.com1.z0.glb.clouddn.com/"+key);
//			newResource.setCreatedTime(DateUtils.now());
//			
//			resourceService.save(newResource);
//		}
		
		userService.updateAvatar(userId, key);
		
		Map<String, String> result = new HashMap<String, String>();
		result.put("key", key);
		result.put("hash", hash);
		result.put("url", AppProerties.HOST_STATIC+key);
		return result;
	}
	
	
	@RequestMapping(method=RequestMethod.POST, value="/avatar")
	public @ResponseBody ResultEntity updateAvatar(@RequestParam("avatar") MultipartFile file) {
		
		try {
			if ( file == null || file.isEmpty() || file.getSize() == 0) {
				return resultEntity.failure(Result.ILLEGAL_DATA);
			}
			String url = super.uploadAvatar(file, super.getUserId());
			
			//这里要更新数据库
			userService.updateAvatar(super.getUserId(), url);
			
			return resultEntity.success(url);
		} catch (Exception e) {
			logger.error("upload avatar error!", e);
			return resultEntity.failure(Result.UPDATE_FAILURE);
		}
	}
}
